<!--
 * @页面名称:
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="page">
    <!-- 验证码处理逻辑 -->
    <div class="mask" v-if="showMask">
      <div class="mask-input">
        <p style="font-weight: 700">请输入验证码:</p>
        <el-row :gutter="15">
          <el-col :span="18">
            <el-input v-model="codeInput"></el-input>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" block @click="validateCode">确定</el-button>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="preview">
      <el-container>
        <el-aside style="background: #191a20">
          <el-menu default-active="1" active-text-color="#1890ff">
            <el-menu-item :key="index" v-for="(item, index) in fileList" @click="menuSelect(item)">
              <el-icon><Files /></el-icon>
              <span>{{ item.AI_Name }}</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <el-container>
          <el-header style="height: 40px; background: #191a20; color: #bdbdc0; text-align: center; line-height: 40px">{{
            title
          }}</el-header>
          <el-main style="padding: 0">
            <div class="pdf-content">
              <!-- 电子文件预览模块(主要指pdf等文件) -->
              <iframe v-if="showFileType === 'pdf'" :src="src" width="100%" height="100%" frameborder="0"></iframe>
              <!-- 图片展览模块 -->
              <img-viewer v-if="showFileType === 'img'" :images="imgList" />
              <!-- 视频预览模块 -->
              <div v-else-if="['video', 'audio'].includes(showFileType)" style="width: 80%; margin: auto">
                <vue-plyr v-if="showFileType === 'audio'">
                  <audio controls playsinline>
                    <source :src="audioSrc" type="audio/mp3" />
                  </audio>
                </vue-plyr>
                <vue-plyr v-else>
                  <video controls playsinline>
                    <source size="720" :src="videoSrc" type="video/mp4" />
                  </video>
                </vue-plyr>
              </div>
              <!-- txt预览页面 -->
              <iframe
                style="background: #fff"
                v-if="showFileType === 'txt'"
                :src="txtSrc"
                width="100%"
                height="100%"
                frameborder="0"
              ></iframe>
              <!-- xml和Json预览模块 -->
              <div v-else-if="showFileType === 'xml'" class="xmlCode">
                <codemirror v-model:value="xmlCode" :tabSize="2" :options="editorOption"> </codemirror>
              </div>
              <!-- ofd预览 -->
              <iframe v-if="showFileType === 'ofd'" :src="ofdSrc" width="100%" height="100%" frameborder="0"></iframe>
            </div>
          </el-main>
        </el-container>
      </el-container>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { ref, reactive, onMounted } from "vue";
import { preType, imgType, videoType, audioType, xmlType, txtType, jsonType, ofdType } from "@/components/Preview/ts/contentType";
// import ImgViewer from "./components/ImgViewer.vue";
import vkbeautify from "vkbeautify";
// json和xml预览插件
import Codemirror from "codemirror-editor-vue3";
// 编辑器代码格式
import "codemirror/mode/javascript/javascript.js";
// 自动刷新(防止codemirror需要手动刷新才出数据)
import "codemirror/addon/display/autorefresh";
import { useRoute } from "vue-router";
import useCurrentInstance from "@/utils/useCurrentInstance";
import ImgViewer from "./ImgPreview.vue";
import ACrypto from "@/utils/crypto";

const { proxy } = useCurrentInstance();
const route = useRoute();
// 是否显示验证码框
const showMask = ref(false);
// 验证码绑定字段
const codeInput = ref("");
//文件类型
const showFileType = ref("pdf");
//pdf预览地址
const src = ref("");
// 全文信息
const fileList = ref([]);
// 头部文字
const title = ref("");
// 全文验证码
const validate_Code = ref("");
// 是否下载
const isDownload = ref(false);
// 是否打印
const isPrint = ref(false);
// 水印文字
const watermarkText = ref("");
// 图片集合
const imgList = ref([]) as any;
// 音频地址
const audioSrc = ref("");
//视频地址
const videoSrc = ref("");
const xmlCode = ref("");
//txt文件地址
const txtSrc = ref("");
// ofd文件地址
const ofdSrc = ref<any>("");
// xml和Json预览配置
const editorOption = reactive({
  // 代码编辑框配置
  autorefresh: true,
  tabSize: 4,
  mode: "text/javascript",
  // theme: "ayu-mirage",
  line: true,
  viewportMargin: Infinity, //处理高度自适应时搭配使用
  highlightDifferences: true,
  autofocus: false,
  indentUnit: 2,
  smartIndent: true,
  readOnly: true, // 只读
  showCursorWhenSelecting: true,
  firstLineNumber: 1
});
// 验证验证码
const validateCode = () => {
  proxy.$vueAxios
    .get("MasterBaseBorrowUrl/IsVerifyCode", { id: route.query.key, verifyCode: codeInput.value })
    .then((res: any) => {
      if (res.Mark) {
        showMask.value = false;
        for (let i = 0; i < fileList.value.length; i++) {
          const item = fileList.value[i];
          getPreviewInfo(item["AI_ID"], preType[item["AI_Source_Extension"]]);
          title.value = item["AI_Name"];
        }
      } else {
        proxy.$message.warning(res.Msg);
      }
    });
};
// 获取全文信息
const getAllInfo = async () => {
  await proxy.$vueAxios.get("MasterBaseBorrowUrl/GetPreviewInfo", { previewKey: route.query.key }).then((res: any) => {
    fileList.value = res.Model.PreviewFiles;
    isDownload.value = res.Model.BU_IsDownload;
    isPrint.value = res.Model.BU_IsPrint;
    watermarkText.value = res.Model.BU_WaterMark;
    if (res.Model.BU_IsEnable) {
      if (new Date(res.Model.BU_ExpireDate).getTime() > new Date().getTime()) {
        if (res.Model.BU_Enable_Verification_Code) {
          showMask.value = true;
          validate_Code.value = res.Model.BU_Verification_Code;
        } else {
          for (let i = 0; i < fileList.value.length; i++) {
            const item = fileList.value[i];
            getPreviewInfo(item["AI_ID"], preType[item["AI_Source_Extension"]]);
          }
          // getPreviewInfo(fileList.value[0]["AI_ID"], preType[fileList.value[0]["AI_Source_Extension"]]);
        }
      } else {
        proxy.$message.warning("该连接已过期");
      }
    } else {
      proxy.$message.warning("该连接未启用");
    }
  });
};
// 获取预览信息
const getPreviewInfo = async (aiId: string, type: string) => {
  await proxy.$vueAxios.get("MasterBaseBorrowUrl/PreviewBorrowFile", { urlId: route.query.key, aiId: aiId }).then((res: any) => {
    if (["application/pdf"].includes(type.toLowerCase())) {
      // 展示pdf类型
      showFileType.value = "pdf";
      const preFile = import.meta.env.VITE_STATIC + res.Model.Path;
      src.value = `/pdfjs/web/viewer.html?file=${encodeURIComponent(preFile)}&print=${isPrint.value}&download=${
        isDownload.value
      }`;
    } else if (imgType.includes(type.toLowerCase())) {
      showFileType.value = "img";
      imgList.value = [res.Model];
      // 图片展示
      imgList.value.forEach((item: { Path: string }) => {
        item.Path = import.meta.env.VITE_STATIC + ACrypto.getSS(item.Path);
      });
    } else if (ofdType.includes(type.toLowerCase())) {
      // ofd预览
      showFileType.value = "ofd";
      console.log(res.Model);
      const preFile = import.meta.env.VITE_STATIC + ACrypto.getSS(res.Model.Path);
      // ofdSrc.value = preFile;
      ofdSrc.value = `/sc-reader/viewer.html?file=${encodeURIComponent(preFile)}&SearchText=${"上海市"}`;
    } else if (videoType.includes(type.toLowerCase())) {
      // 视频展示
      showFileType.value = "video";
      videoSrc.value = import.meta.env.VITE_STATIC + ACrypto.getSS(res.Model.Path);
    } else if (audioType.includes(type.toLowerCase())) {
      showFileType.value = "audio";
      audioSrc.value = import.meta.env.VITE_STATIC + ACrypto.getSS(res.Model.Path);
    } else if (txtType.includes(type.toLowerCase())) {
      // txt文件预览展示
      const preFile = import.meta.env.VITE_STATIC + ACrypto.getSS(res.Model.Path);
      showFileType.value = "txt";
      axios({
        url: preFile,
        method: "get",
        responseType: "blob"
      }).then(res => {
        const fileReader = new FileReader();
        fileReader.readAsDataURL(res.data);
        fileReader.onload = (e: any) => {
          txtSrc.value = e.target.result;
        };
      });
    } else if (xmlType.includes(type.toLowerCase())) {
      // xml和json文件直接预览展示
      const preFile = import.meta.env.VITE_STATIC + ACrypto.getSS(res.Model.Path);
      showFileType.value = "xml";
      axios.get(preFile).then(res => {
        if (jsonType.includes(type.toLowerCase())) {
          xmlCode.value = vkbeautify.json(res.data);
        } else {
          xmlCode.value = vkbeautify.xml(res.data);
        }
      });
    } else {
      proxy.$message.error("暂不支持该文件类型");
    }
  });
};
// 菜单点击事件
const menuSelect = (item: any) => {
  showFileType.value = "";
  getPreviewInfo(item.AI_ID, preType[item.AI_Source_Extension]);
  title.value = item.AI_Name;
};
onMounted(() => {
  getAllInfo();
});
</script>

<style lang="scss" scoped>
.page {
  position: relative;
  width: 100%;
  height: 100%;
  .mask {
    z-index: 100;
    height: 100%;
    width: 100%;
    position: absolute;
    background: rgba(255, 255, 255, 1);
    .mask-input {
      position: absolute;
      width: 30%;
      height: 300px;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
    }
  }
}
.preview {
  width: 100%;
  height: 100%;
  display: flex;
}
.pdf-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
// .el-menu-item:active {
//   background-color: #1890ff;
//   color: #fff;
// }
</style>
